package com.yequan.leetcode.tree.postordertraversal_145;

import com.yequan.leetcode.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author : Administrator
 * @date : 2020/3/25
 */
public class PostorderTraversal {


    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);
        return res;
    }

    private void helper(TreeNode root, List<Integer> res) {
        if (null != root) {
            if (null != root.left) {
                helper(root.left, res);
            }
            if (null != root.right) {
                helper(root.right, res);
            }
            res.add(root.val);
        }
    }

    /**
     * 还有问题
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (null != root) {
            stack.push(root);
        }
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (null != node.right) {
                stack.push(node.right);
            }
            if (null != node.left) {
                stack.push(node.left);
            }
            res.add(node.val);
        }
        return res;
    }

}
